<?php

declare(strict_types=1);



namespace App\Music\Faith;

use Exception;
use Hyperf\Stringable\Str;

final class Utils
{
    /**
     */
    public static function getDefaultSaveDir(): string
    {
        $saveDir = BASE_PATH . '/storage/';

        if (! is_dir($saveDir) && ! mkdir($saveDir, 0755, true) && ! is_dir($saveDir)) {
            throw new \RuntimeException(sprintf('The directory "%s" was not created.', $saveDir));
        }

        return $saveDir;
    }

    /**
     * 获取下载地址
     */
    public static function getSavePath(array $song, ?string $saveDir = null, string $defaultExt = 'mp3'): string
    {
        $saveDir = Str::finish($saveDir ?? self::getDefaultSaveDir(), \DIRECTORY_SEPARATOR);

        if (! is_dir($saveDir) && ! mkdir($saveDir, 0755, true) && ! is_dir($saveDir)) {
            throw new \RuntimeException(sprintf('The directory "%s" was not created.', $saveDir));
        }
        return sprintf(
            '%s%s - %s.%s',
            $saveDir,
            implode(',', $song['artist']),
            $song['name'],
            $defaultExt ?: pathinfo(parse_url($song['url'], PHP_URL_PATH), PATHINFO_EXTENSION)
        );
    }

    /**
     * 生成歌曲地址
     * */
    public static function buildUrl($music_name): string
    {
        $music_name = str_replace('/', '_', $music_name);
        // 文件路径
        $file_path = self::getDefaultSaveDir() . 'lyrics/';
        return $file_path . "$music_name.txt";
    }

    /**
     * 设置歌词
     * @param $music_name
     * @param string $lyric
     * return string url地址
     * @return bool
     * @throws Exception
     */
    public static function setLyric($music_name, string $lyric = '')
    {
        if (!$music_name) {
            throw new Exception('歌曲名不能为空');
        }

        $filename = self::buildUrl($music_name);
        // 将歌词内容保存到txt文件
        if (!file_put_contents($filename, $lyric)) {
            throw new Exception('歌词保存失败');
        }
        return $filename;
    }

    /**
     * 获取歌词
     * @param string $music_name
     * @return string
     */
    public static function getLyric(string $music_name): string
    {
        $filename = self::buildUrl($music_name);
        try {
            $lyricsFromFile = file_get_contents($filename) ?: '暂无歌词';
        } catch (\Exception $exception) {
            $lyricsFromFile = '暂无歌词';
        }
        return $lyricsFromFile;
    }

    /**
     * 判断是否存在歌词文件
     * */
    public static function isExistLyric($music_name): bool
    {
        $file_name = self::buildUrl($music_name);
        // 判断文件是否存在
        if (!file_exists($file_name)) {
            return false;
        }
        return true;
    }

    /**
     * QQ音乐设置cookie
     * */
    public static function tencentParse($cookies)
    {
        try {
            if (is_string($cookies)) {
                $cookieObj = array();
                $cookiesArr = explode('; ', $cookies);
                foreach ($cookiesArr as $c) {
                    $arr = explode('=', $c);
                    $key = $arr[0];
                    $value = $arr[1];
                    if (count($arr) > 2) {
                        array_shift($arr);
                        $value = implode('=', $arr);
                    }
                    $cookieObj[$key] = $value;
                }
                return $cookieObj;
            } else if (is_array($cookies)) {
                return $cookies;
            } else {
                throw new \Exception("parse error");
            }
        } catch (\Exception $e) {
            throw new \Exception('Cookie:parse_error', 0);
        }
    }

    /**
     * QQ音乐获取cookie
     * */
    public static function serialization($data)
    {
        $cookie = '';
        foreach ($data as $key => $value) {
            $s = urlencode($key) . '=' . urlencode($value) . '; ';
            $cookie .= $s;
        }
        if ($cookie === '') {
            throw new \Exception('Cookie:serialization_error');
        }
        return substr($cookie, 0, strlen($cookie) - 2);
    }

}
